<template>
  <div>
    <!-- <el-breadcrumb separator="|">xxxx</el-breadcrumb> -->
    <el-row>
      <el-col v-show="breadcrumbs.length > 1" :span="1" style="text-align: center;color: #409eff;">
        <i class="el-icon-back" />
      </el-col>
      <el-col :span="23">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index">
            <a :style="index === (breadcrumbs.length-1) ? '' : 'color: #409eff;'" @click="handleBreadcrumb(item)">{{ item.alias }}</a>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
  </div>
</template>

<script>
const breadcrumb = {
  name: 'All Files',
  alias: 'All Files',
  parentPath: '/'
}

export default {
  name: 'FileBreadcrumb',
  data() {
    return {
      breadcrumbs: []
    }
  },
  created() {
    this.breadcrumbs = [breadcrumb]
    this.$on('setBreadcrumb', this.setBreadcrumb)
  },
  methods: {
    /**
     * 处理面包屑点击事件
     *
     * @param {Object} item
     */
    handleBreadcrumb(item) {
      this.setBreadcrumb(item.parentPath)
      this.$emit('handleBreadcrumb', item)
    },
    /**
     * 设置文件路径面包屑
     *
     * @param {String} parentPath 父路径
     */
    setBreadcrumb(parentPath) {
      this.breadcrumbs = []
      if (parentPath && parentPath !== '/') {
        // count===0时，表示为最后一个
        let count = 0
        while (parentPath.includes('/')) {
          const i = parentPath.lastIndexOf('/')
          const name = parentPath.substring(i + 1, parentPath.length)
          const bread = {
            name,
            parentPath,
            alias: name.length < 7 || count === 0 ? name : name.substring(0, 6) + '...'
          }
          this.breadcrumbs = [bread, ...this.breadcrumbs]
          parentPath = parentPath.substring(0, i)
          count++
        }
      }
      this.breadcrumbs = [breadcrumb, ...this.breadcrumbs]
    }
  }
}
</script>
